package controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.WebmailModel;
import models.WebsiteModel;

import entities.Webmail;
import entities.Website;
import forms.WebsiteForm;

public class WebsiteAddServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		Website website = new Website();
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		request.setAttribute("check", check);
		request.setAttribute("website", website);
		request.setAttribute("form", "add");
		try {
			request.getRequestDispatcher("/pages/website_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		WebsiteModel websiteModel = WebsiteModel.getInstance();
		Website website = new Website();
		
		//Get value form and check valid
		TreeMap form = WebsiteForm.checkValid(request, website);
		website = (Website) form.get("website");
		TreeMap<String, String>  check = (TreeMap) form.get("checkValid");
		
		//Save data
		if (check.size() == 0){
			website.setId(IdUniqueHelper.getId());
			websiteModel.insert(website);
			
			//Set to webmail
			WebmailModel webmailModel = WebmailModel.getInstance();
			Webmail webmail = new Webmail();
			webmail.setId(website.getId());
			webmailModel.insert(webmail);
			
			request.setAttribute("success", "Add success website " + website.getId());
			website = new Website();
		}
		
		request.setAttribute("check", check);
		request.setAttribute("website", website);
		request.setAttribute("form", "add");
		try {
			request.getRequestDispatcher("/pages/website_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
